﻿#region Using Directives

using System;
using System.IO;
using System.Windows.Forms;
using System.Globalization;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Library;
using Microsoft.Practices.RecipeFramework.Services;
using Microsoft.Practices.RecipeFramework.VisualStudio;
using Microsoft.Practices.RecipeFramework.VisualStudio.Templates;
using EnvDTE;
using System.Diagnostics;

#endregion

namespace SteriaMummert.SharePoint.SoftwareFactoryLite.Actions
{
    [ServiceDependency(typeof(DTE))]
    public class AddKeyFileToSolution : ConfigurableAction
    {
        [Input(Required = true)]
        public bool EnableStrongNaming
        {
            get { return _EnableStrongNaming; }
            set { _EnableStrongNaming = value; }
        }
        private bool _EnableStrongNaming = false;

        [Input(Required = true)]
        public string KeyFileName
        {
            get { return _KeyFileName; }
            set { _KeyFileName = value; }
        }
        private string _KeyFileName = "";

        protected string GetBasePath()
        {
            return base.GetService<IConfigurationService>(true).BasePath;
        }


        public override void Execute()
        {
            string snPath = GetBasePath() + "\\sn.exe";

            if (this.EnableStrongNaming)
            {
                EnvDTE.DTE vs = this.GetService<EnvDTE.DTE>(true);
                string solutionPath = (string)vs.Solution.Properties.Item("Path").Value;
                string solutionDir = Path.GetDirectoryName(solutionPath);
                string keyFilePath = Path.Combine(solutionDir, this.KeyFileName);

                // Make sure the directory exists.
                Directory.CreateDirectory(Path.GetDirectoryName(keyFilePath));

                // Launch the process and wait until it's done (with a 10 second timeout).
                ProcessStartInfo startInfo = new ProcessStartInfo(snPath, string.Format("-k \"{0}\"", keyFilePath));
                startInfo.CreateNoWindow = true;
                startInfo.UseShellExecute = false;
                System.Diagnostics.Process snProcess = System.Diagnostics.Process.Start(startInfo);
                snProcess.WaitForExit(20000);

                try
                {
                    // Add the key file to the Solution Items.
                    DteHelper.SelectSolution(vs);
                    vs.ItemOperations.AddExistingItem(keyFilePath);
                    // The AddExistingItem operation also shows the item in a new window, close that.
                    vs.ActiveWindow.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo);
                }
                catch (Exception)
                {
                }                
            }
        }

        public override void Undo()
        {
        }
    }
}